/**
 * @Filename: stopwatch.cpp
 * @Description:
 * @Author: chengxiaojun
 * @Email: csforgood@gmail.com
 * @Time: 2011/11/11
 */
#include  "stopwatch.h"

Stopwatch::Stopwatch(bool start_running) : m_running(false) {
	memset(&elapsed_time, 0, sizeof(elapsed_time));
	if (start_running)
		start();
}

void Stopwatch::start() {
	if (!m_running) {
		boost::xtime_get(&start_time, boost::TIME_UTC);
		m_running = true;
	}
}

void Stopwatch::stop() {
	if (m_running) {
		boost::xtime_get(&stop_time, boost::TIME_UTC);
		if (start_time.sec == stop_time.sec)
			elapsed_time.nsec += stop_time.nsec - start_time.nsec;
		else {
			elapsed_time.sec += stop_time.sec - start_time.sec;
			elapsed_time.nsec += (1000000000L - start_time.nsec) + stop_time.nsec;
			if (elapsed_time.nsec > 1000000000L) {
				elapsed_time.sec += elapsed_time.nsec / 1000000000L;
				elapsed_time.nsec %= 1000000000L;
			}
		}
		m_running = false;
	}
}

void Stopwatch::reset() { memset(&elapsed_time, 0, sizeof(elapsed_time)); }

double Stopwatch::elapsed() {
	if (m_running) {
		stop();
		start();
	}
	return (double)elapsed_time.sec
		+ ((double)elapsed_time.nsec / 1000000000.0);
}
int64_t Stopwatch::interval() {
	if (m_running) {
		stop();
		start();
	}
	return elapsed_time.sec * 1000000000
		+ elapsed_time.nsec;
}

int64_t Stopwatch::get_start_time(){
       return start_time.sec;
}
int64_t Stopwatch::get_stop_time(){
       return stop_time.sec;
}
